import React, {useEffect, useState, memo, useRef} from 'react'
import {
	Button,
	message,
	Popconfirm,
	Tag,
	Row,
	Col,
	Form,
	Modal,
	Select,
	Image,
} from 'antd'

import type {ColumnsType} from 'antd/es/table'
import {history, connect} from 'umi'
import Permissions from '@/components/Permissions'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import {
	getTableList,
	changeStuts,
	deleteManage,
} from '@/service/workflow/manage'
import {getDict} from '@/service/common/dict'
import {formatDate} from '@/utils/common/dateFilter'

const formItemLayout = {
	labelCol: {flex: '80px'},
	wrapperCol: {flex: '1'},
}

const contract = memo((props: {user: {orgId: string | number}}) => {
	const {orgId} = props.user
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [selectId, setSelectId] = useState('')
	const [loading, setLoading] = useState(false)
	const [dict, setDict] = useState({
		Process_Type: [],
	})
	const [tableList, setTableList] = useState<any[]>([])
	const [total, setTotal] = useState(0)

	const [searchData, setSearchData] = useState({})
	const [formData, setFormData] = useState<any[]>([])
	const [form] = Form.useForm()
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [isModalOpenImg, setIsModalOpenImg] = useState(false)
	const [isModalOpenImgId, setIsModalOpenImgId] = useState('')
	const [setStutaId, setSetStutaId] = useState('')

	// 获取表格数据
	const onListFun = () => {
		setLoading(true)
		getTableList({...params, ...searchData, id: orgId})
			.then((res: any) => {
				if (res.success) {
					if (res?.data?.records) {
						setTableList(() => res?.data?.records)
						setTotal(res?.data?.total)
					} else {
						setTableList(() => [])
						setTotal(0)
					}
					setLoading(false)
				}
			})
			.catch(() => {
				setLoading(false)
			})
	}

	useEffect(() => {
		getDict(
			{
				dictKeys: ['Process_Type'],
			},
			(res: any) => {
				setDict(() => res)
			},
		)
	}, [])

	// 删除事件
	const onDeleteFun = (ids?: any) => {
		const sid: string = ids || selectId
		deleteManage({id: sid})
			.then((res) => {
				if (res?.success) {
					message.success(res.msg)
					onListFun()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}

	// 列表
	const columns: ColumnsType<contractAPI.ContractColumns> = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text, record, index) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '租户编号',
			dataIndex: 'tenantId',
			align: 'center',
			width: 90,
			render: (text) => <Tag color="processing">{text}</Tag>,
		},
		{
			title: '流程主键',
			dataIndex: 'id',
			align: 'center',
			width: 450,
			ellipsis: true,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '流程标识',
			dataIndex: 'key',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '流程名称',
			dataIndex: 'name',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text) => <span>{text || '--'}</span>,
		},
		{
			title: '流程分类',
			dataIndex: 'category',
			align: 'center',
			width: 150,
			render: (text: number, record: any) => (
				<>
					{dict?.Process_Type?.map(
						(item: {dictKey: number; dictValue: string}) => {
							if (Number(item?.dictKey) === Number(text)) {
								return (
									<Tag color="processing" key={record?.id}>
										{item?.dictValue}
									</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '流程版本',
			dataIndex: 'version',
			align: 'center',
			width: 150,
			render: (text) => <Tag color="processing">v{text}</Tag>,
		},
		{
			title: '状态',
			dataIndex: 'isSuspended',
			align: 'center',
			width: 150,
			render: (text, record: any) => {
				if (!record?.isSuspended) {
					return <Tag color="processing">激活</Tag>
				}
				return <Tag color="error">挂起</Tag>
			},
		},
		{
			title: '部署时间',
			dataIndex: 'deployTime',
			align: 'center',
			width: 250,
			ellipsis: true,
			render(text) {
				return (
					<span>
						{text ? formatDate(text, 'YYYY-MM-DD HH:mm:ss') : '--'}
					</span>
				)
			},
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 300,
			render: (text, record: any) => (
				<div>
					<Permissions permissionID="amc_system_workflow_manage_status">
						<Button
							type="link"
							size="small"
							onClick={() => {
								form.setFieldsValue({
									id: record.id,
									type: !record.isSuspended,
								})
								setSetStutaId(() => record.id)
								setIsModalOpen(true)
							}}>
							变更状态
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_workflow_manage_chart">
						<Button
							type="link"
							size="small"
							onClick={() => {
								setIsModalOpenImgId(() => record.id)
								setIsModalOpenImg(true)
							}}>
							流程图
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_workflow_manage_delete">
						<Popconfirm
							placement="topLeft"
							title="你确定要删除这条数据吗？"
							onConfirm={() => onDeleteFun(record.id)}
							okText="确定"
							cancelText="取消">
							<Button type="link" size="small">
								删除
							</Button>
						</Popconfirm>
					</Permissions>
					<Permissions permissionID="amc_system_workflow_manage_reviewed">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/workflow/manage/reviewed',
									query: {
										key: record?.category,
									},
								})
							}}>
							审核人
						</Button>
					</Permissions>
				</div>
			),
		},
	]

	const onFinish = (values: any) => {
		setSearchData(values)
	}

	// 初始化分页
	useEffect(() => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}, [searchData])
	// 获取表格数据
	// 自定义一个初始不更新的hook
	const useUpdateEffect = (fn: Function, inputs: any[]) => {
		const didMountRef = useRef(false)
		useEffect(() => {
			if (didMountRef.current) fn()
			else didMountRef.current = true
		}, inputs)
	}

	// 使用自定义hook
	useUpdateEffect(onListFun, [params])

	// 搜索重置
	const onReset = () => {
		setSearchData({})
	}
	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'select',
						label: '流程分类',
						name: 'type',
						key: 'type',
						keys: 'dictKey',
						title: 'dictValue',
						items: [
							{
								dictKey: '2',
								dictValue: '激活',
							},
							{
								dictKey: '1',
								dictValue: '挂起',
							},
						],
					},
					{},
					{},
				],
			},
		]
		setFormData(formItems)
	}, [])

	const submit = async () => {
		const form1 = await form.validateFields()
		const type = form1?.type ? 2 : 1
		changeStuts({type, id: setStutaId})
			.then((res: any) => {
				if (res.success) {
					message.success('变更状态成功')
					form.resetFields()
					setIsModalOpen(false)
					onListFun()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}
	const onCancel = () => {
		form.resetFields()
		setIsModalOpen(false)
	}

	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="table">
				<CustomTable
					params={params}
					columns={columns}
					kid="id"
					pagination
					total={total}
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					scroll={{y: 480}}
					loading={loading}
					dataSource={tableList}
					showRowSelection
					selectCallback={(keys: any) => {
						setSelectId(() => keys?.join(','))
					}}
				/>
			</div>
			<Modal
				title="流程部署配置"
				open={isModalOpen}
				onOk={submit}
				onCancel={onCancel}
				width={500}
				destroyOnClose
				footer={
					<>
						<Button size="small" onClick={onCancel}>
							取消
						</Button>
						<Button type="primary" size="small" onClick={submit}>
							确定
						</Button>
					</>
				}>
				<Form
					form={form}
					name="basic"
					layout="horizontal"
					labelCol={{flex: '90px'}}
					labelAlign="right"
					labelWrap
					initialValues={{remember: true}}
					autoComplete="off">
					<Row gutter={12}>
						<Col span={24}>
							<Form.Item
								label="流程类型"
								name="type"
								rules={[
									{
										required: true,
									},
								]}>
								<Select
									placeholder="请选择"
									allowClear
									options={[
										{
											value: true,
											label: '激活',
										},
										{
											value: false,
											label: '挂起',
										},
									]}
								/>
							</Form.Item>
						</Col>
					</Row>
				</Form>
			</Modal>

			<Modal
				title="流程图"
				open={isModalOpenImg}
				onOk={() => {
					setIsModalOpenImg(false)
				}}
				onCancel={() => {
					setIsModalOpenImg(false)
				}}
				width={800}
				destroyOnClose
				footer={
					<>
						<Button
							onClick={() => {
								setIsModalOpenImg(false)
							}}>
							取消
						</Button>
					</>
				}>
				<Image
					preview={false}
					// src={`${
					// 	window.apiPrefixUri || ''
					// }/workflow/api/promise/process/processFile?id=${isModalOpenImgId}`}
					src={`${
						window.apiPrefixUri || ''
					}/workflow/api/promise/process/processFile?id=${isModalOpenImgId}`}
				/>
			</Modal>
		</div>
	)
})

export default connect(({user}: any) => ({user}))(contract)
